package linfei.controller;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import linfei.pojo.Admin;
import linfei.pojo.Books;
import linfei.pojo.Order;
import linfei.service.BooksMapperService;
import linfei.service.OrderMapperService;
import linfei.util.ResultGridStore;
import linfei.util.ResultMsg;
/**
 * 订单-控制层
 * 
 * @author 林飞
 * @author wfeil211@foxmail.com
 */
@Controller
@RequestMapping("OrderController")
public class OrderController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(OrderController.class);
	@Autowired
	private OrderMapperService orderMapperService;
	@Autowired
	private BooksMapperService booksMapperService;
	/**
	 * 表单获取
	 * @param order
	 * @param start
	 * @param limit
	 * @return ResultGridStore
	 */
	@RequestMapping("/getGridStore")
	@ResponseBody
	public ResultGridStore getGridStore(Order order,Integer start,Integer limit,HttpServletRequest req){
		ResultGridStore rgs=new ResultGridStore();
		try{
			Admin admin=(Admin) req.getSession().getAttribute("adm");
			if(order.getAdminid()==null){
				if(admin.getIdentity()!=1){
					//若不是管理员，添加订单筛选
					order.setAdminid(admin.getId());
				}
			}			
			rgs.setList(orderMapperService.serviceQuery(order, start, limit));
			rgs.setTotalProperty(orderMapperService.serviceTotal(order));
		}catch(Exception e){
			e.printStackTrace();
			logger.error("系统出错!", e);
		}
		return rgs;
	}
	/**
	 * 借阅图书(添加订单)
	 * @param ids
	 * @return ResultMsg
	 */
	@RequestMapping("/addOrder")
	@ResponseBody
	public ResultMsg addOrder(Order order,HttpServletRequest req){
		ResultMsg msg = new ResultMsg();
		try {
			String orderno = UUID.randomUUID().toString().replace("-", "").toLowerCase();
			order.setOrderno(orderno);
			order.setBorstuts(0);
			order.setCreatetime(new Date());
			Admin admin=(Admin) req.getSession().getAttribute("adm");
			order.setAdminid(admin.getId());
			//减库存
			Books books=new Books();
			books.setIsbn(order.getIsbn());
			Books book=(booksMapperService.serviceQuery(books, 0, 1)).get(0);
			if(book.getNum()<order.getNum()){
				msg.setExecute(false);
				msg.setSuccess(false);
				msg.setMsg("图书数量不足，请重输!");
				return msg;
			}
			book.setNum(book.getNum()-order.getNum());
			booksMapperService.serviceUpdateByPrimaryKey(book);
			orderMapperService.serviceInsert(order);
			msg.setExecute(true);
			msg.setSuccess(true);
			msg.setMsg("借阅成功!");
		} catch (Exception e) {
			msg.setExecute(false);
			msg.setSuccess(false);
			msg.setMsg("系统出错!");
			e.printStackTrace();
			logger.error("系统出错!", e);
		}
		return msg;
	}
	/**
	 * 借出
	 * @param ids
	 * @return ResultMsg
	 */
	@RequestMapping("/outBooks")
	@ResponseBody
	public ResultMsg outBooks(String ids){
		ResultMsg msg = new ResultMsg();
		try {
			if (!(StringUtils.isEmpty(ids))) {
				String[] value=ids.split(",");
				for(int i=0;i<value.length;i++){
					Order order=orderMapperService.serviceSelectByPrimaryKey(Integer.parseInt(value[i]));
					order.setBorstuts(1);
					orderMapperService.serviceUpdateByPrimaryKey(order);
				}
				msg.setExecute(true);
				msg.setSuccess(true);
				msg.setMsg("借出成功!");				
		} else {
			msg.setExecute(false);
			msg.setSuccess(false);
			msg.setMsg("数据传输失败!");
		}
		} catch (Exception e) {
			msg.setExecute(false);
			msg.setSuccess(false);
			msg.setMsg("系统出错!");
			e.printStackTrace();
			logger.error("系统出错!", e);
		}
		return msg;
	}
	/**
	 * 归还
	 * @param ids
	 * @return ResultMsg
	 */
	@RequestMapping("/inBooks")
	@ResponseBody
	public ResultMsg inBooks(String ids){
		ResultMsg msg = new ResultMsg();
		try {
			if (!(StringUtils.isEmpty(ids))) {
				String[] value=ids.split(",");
				for(int i=0;i<value.length;i++){
					Order order=orderMapperService.serviceSelectByPrimaryKey(Integer.parseInt(value[i]));
					order.setBorstuts(2);
					orderMapperService.serviceUpdateByPrimaryKey(order);
					//加库存
					Books books=new Books();
					books.setIsbn(order.getIsbn());
					Books book=(booksMapperService.serviceQuery(books, 0, 1)).get(0);
					book.setNum(book.getNum()+order.getNum());
					booksMapperService.serviceUpdateByPrimaryKey(book);
				}
				msg.setExecute(true);
				msg.setSuccess(true);
				msg.setMsg("归还成功!");				
		} else {
			msg.setExecute(false);
			msg.setSuccess(false);
			msg.setMsg("数据传输失败!");
		}
		} catch (Exception e) {
			msg.setExecute(false);
			msg.setSuccess(false);
			msg.setMsg("系统出错!");
			e.printStackTrace();
			logger.error("系统出错!", e);
		}
		return msg;
	}
	/**
	 * 导出到Excel表格-桌面
	 * @param month
	 * @return ResultMsg
	 */
	@RequestMapping("export")
	@ResponseBody
	public ResultMsg export(HttpServletRequest req,HttpServletResponse response){
		response.setContentType("application/binary;charset=UTF-8");
		ResultMsg msg=new ResultMsg();
		try{
			Order order=new Order();
			Admin admin=(Admin) req.getSession().getAttribute("adm");
			if(admin.getIdentity()!=1){
				//若不是管理员，添加订单筛选
				order.setAdminid(admin.getId());
			}
			List<Order> list=orderMapperService.serviceQuery(order, 0, 100);
			String title[]=new String[10];
			if(list.size()!=0){
				title[0]="序号";
				title[1]="订单号";
				title[2]="所属用户编号";
				title[3]="图书名称";
				title[4]="手机号";
				title[5]="借阅时间";
				title[6]="数量";
				title[7]="归还时间";
				title[8]="ISBN";
				title[9]="借阅状态";
			}else{
				title[0]="没有记录";
				title[1]="没有记录";
				title[2]="没有记录";
				title[3]="没有记录";
				title[4]="没有记录";
				title[5]="没有记录";
				title[6]="没有记录";
				title[7]="没有记录";
				title[8]="没有记录";
				title[9]="没有记录";
			}
			String content[][] = new String[list.size()][title.length];
				for (int i = 0; i < list.size(); i++) {									
					Order obj = list.get(i);
		            content[i][0] = obj.getId()+"";
		            content[i][1] = obj.getOrderno()+"";
		            content[i][2] = obj.getAdminid()+"";
		            content[i][3] =obj.getName()+"";
			        content[i][4] =obj.getPhone()+"";
			        content[i][5] =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj.getCreatetime())+"";
			        content[i][6] =obj.getNum()+"";
			        content[i][7] =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj.getGobacktime())+"";
			        content[i][8] =obj.getIsbn()+"";
			        if(obj.getBorstuts()==0) {
			        	content[i][9] ="待借出";
			        }else if(obj.getBorstuts()==1) {
			        	content[i][9] ="已借出";
			        }else if(obj.getBorstuts()==2) {
			        	content[i][9] ="已归还";
			        }		          	            
			}
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet("订单信息");
			sheet.autoSizeColumn(2); 
			HSSFRow row = sheet.createRow(0);
			HSSFCellStyle style = wb.createCellStyle();
	        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	        //声明列对象
	        HSSFCell cell = null;
	        //创建标题
	        for(int i=0;i<title.length;i++){
	            cell = row.createCell(i);
	            cell.setCellValue(title[i]);
	            cell.setCellStyle(style);
	        }
	        //创建内容
	        for(int i=0;i<content.length;i++){
	            row = sheet.createRow(i + 1);
	            for(int j=0;j<content[i].length;j++){
	                //将内容按顺序赋给对应的列对象
	                row.createCell(j).setCellValue(content[i][j]);
	            }
	        }
	        //FileOutputStream out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\会员信息.xls");
	        ServletOutputStream out=response.getOutputStream();
	        String fileName=new String(("OrderInfo "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(),"UTF-8");
	        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
	        wb.write(out);
	        out.flush();
	        out.close();
			msg.setExecute(true);
			msg.setMsg("导出到桌面成功!");
		} catch (Exception e) {
			msg.setExecute(false);
			msg.setMsg("导出失败!");
			e.printStackTrace();
		}	
		return msg;
	}
}
